package com.beagle.njddapp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.beagle.njddapp.R;
import com.beagle.njddapp.base.ApiService;
import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.base.RetrofitHttp;
import com.beagle.njddapp.bean.UpdateBean;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.net.BaseHttpResponse;
import com.beagle.njddapp.net.HttpResponseObserver;
import com.beagle.njddapp.net.RxSchedulers;
import com.beagle.njddapp.utils.PrefsManager;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.beagle.njddapp.weight.dialog.MsgDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

import static com.beagle.njddapp.core.UserService.TOKEN;

/**
 * @author hxx
 * @date 2021-03-01 21:25
 * 设置
 */
public class SettingActivity extends AppCompatActivity implements MsgDialog.msgDialogHandleCallback {


    @BindView(R.id.commom_title_tv)
    TextView tvTitle;
    @BindView(R.id.common_container)
    RelativeLayout container;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.prograssBar)
    ProgressBar progressBar;
    private MsgDialog msgDialog;
    private int type; //1 更新 2 注销
    private ApiService apiService;
    private long versionCOde;
    private String versionName;
    private UpdateBean.ResultBean resultBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        StatusBarUtil.immersive(this,Color.WHITE);
        StatusBarUtil.darkMode(this);
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        container.setBackgroundColor(Color.WHITE);
        StatusBarUtil.setPaddingSmart(this,container);
        tvTitle.setText("设置");
        PackageManager pm = getApplicationContext().getPackageManager();//context为当前Activity上下文
        PackageInfo pi = null;
        retrofit2.Retrofit retrofit = RetrofitHttp.provideRetrofit();
        apiService = retrofit.create(ApiService.class);
        try {
            pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
            versionName = pi.versionName;
            tvVersion.setText(pi.versionName);
            versionCOde=pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }



    @OnClick({R.id.tv_logout,R.id.common_back_iv,R.id.rl_yj,R.id.rl_change,R.id.rl_clean,R.id.rl_reset,R.id.rl_exit,R.id.rl_update})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_logout:
                UserService.getInstance().setUserInfoBean(null);
                UserService.getInstance().setRole(-1);
                UserService.getInstance().setToken("");
                UserService.getInstance().setPhone("");
                PrefsManager.getInstance(BaseApplication.getInstance()).putString(TOKEN,"");
                PrefsManager.getInstance(getApplicationContext()).clear();
                tvTitle.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ActivityUtils.finishAllActivities();
                        startActivity(new Intent(SettingActivity.this,LoginActivity.class));
                    }
                },500);
                break;
            case R.id.common_back_iv:
                onBackPressed();
                break;
            case R.id.rl_reset:
                startActivity(new Intent(this,SetPasswordActivity.class));
                break;
            case R.id.rl_update:
                progressBar.setVisibility(View.VISIBLE);
                apiService.newVersion().compose(RxSchedulers.compose()).subscribe(new Observer<UpdateBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }
                    @Override
                    public void onNext(UpdateBean updateBean) {
                        progressBar.setVisibility(View.GONE);
                        if (updateBean!=null&&updateBean.getResult()!=null){
                            resultBean=updateBean.getResult();
                            String code=resultBean.getCode();
                            try {
                                if (Integer.parseInt(code)>versionCOde){
                                   showDIalog();
                                }else {
                                    ToastUtils.showShort("已经是最新版本了");
                                }
                            }catch (Exception e){
                                ToastUtils.showShort("已经是最新版本了");
                            }
                        }else {
                            ToastUtils.showShort("已经是最新版本了");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        progressBar.setVisibility(View.GONE);
                        ToastUtils.showShort("已经是最新版本了");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

                break;
            case R.id.rl_exit:
                type=2;
                if (msgDialog==null){
                    msgDialog=new MsgDialog(this);
                    msgDialog.setMsgDialogHandleCallback(this);
                }
                msgDialog.show();
                msgDialog.update("警告!","当您注销后，您的账号将不复存在，之前的订单与信息均不会保留，是否确认注销操作？","确认注销","取消");
                break;
            case R.id.rl_yj :
                startActivity(new Intent(this,SuggestActivity.class));
                break;
            case R.id.rl_change :
                startActivity(new Intent(this,ChangeRoleActivity.class));
                break;
            case R.id.rl_clean:
                tvTitle.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("清理成功");
                    }
                },2000);
                break;
        }
    }

    private void showDIalog() {
        type=1;
        if (msgDialog==null){
            msgDialog=new MsgDialog(this);
            msgDialog.setMsgDialogHandleCallback(this);
        }
        msgDialog.show();
        msgDialog.update("检查更新","您当前的版本为"+versionName+"，目前APP最新版本为"+resultBean.getVersion()+"，您需要进行更新升级","立即更新","暂不更新");
    }


    @Override
    public void ok() {
        if (type==1){
            progressBar.setVisibility(View.VISIBLE);
            apiService.downloadAPk(resultBean.getUrl()).compose(RxSchedulers.compose()).safeSubscribe(new Observer<ResponseBody>() {
                @Override
                public void onSubscribe(Disposable d) {

                }
                @Override
                public void onNext(ResponseBody responseBody) {
                    progressBar.setVisibility(View.GONE);

                    File file=writeResponseBodyToDisk(responseBody);
                    if ( file!=null){
                        installApk(getApplicationContext(),file);
                    }else {

                    }
                }
                @Override
                public void onError(Throwable e) {
                    progressBar.setVisibility(View.GONE);
                }

                @Override
                public void onComplete() {

                }
            });
        }else {
            progressBar.setVisibility(View.VISIBLE);
            apiService.userExit().compose(RxSchedulers.compose()).subscribe(new HttpResponseObserver<BaseHttpResponse>() {
                @Override
                public void success(BaseHttpResponse o) {
                    ToastUtils.showShort("注销成功");
                    UserService.getInstance().setUserInfoBean(null);
                    UserService.getInstance().setRole(-1);
                    UserService.getInstance().setToken("");
                    UserService.getInstance().setPhone("");
                    PrefsManager.getInstance(BaseApplication.getInstance()).putString(TOKEN,"");
                    PrefsManager.getInstance(getApplicationContext()).clear();
                    tvTitle.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ActivityUtils.finishAllActivities();
                            startActivity(new Intent(SettingActivity.this,LoginActivity.class));
                        }
                    },1000);
                }

                @Override
                public void error(int code, String message) {
                    progressBar.setVisibility(View.GONE);
                    ToastUtils.showShort("注销失败，您存在未完成的订单");
                }
            });
        }
    }

    public  void installApk(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//需要开新的任务栈，不然安装完成无法弹出“完成”、“打开”页面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
            Uri apkUri = FileProvider.getUriForFile(context, "com.beagle.njddapp", apkFile);  //包名.fileprovider
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    private File writeResponseBodyToDisk(ResponseBody body) {
        try {
            File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "njdd.apk");

            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;

                }

                outputStream.flush();

                return futureStudioIconFile;
            } catch (IOException e) {
                return null;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public void cancle() {

    }
}
